//
//  AirportViewModel.swift
//  CitySearch
//
//  Created by guotonglin on 2020/6/3.
//  Copyright © 2020 guotonglin. All rights reserved.
//

import Foundation
import CoreLocation

protocol AirportViewPresentable {
    var name: String { get }
    var code: String { get }
    var address: String { get }
    var distance: Double? { get }
    var formattedDistance: String { get }
    var runawayLength: String { get }
    var location: (lat: String, lon: String) { get }
}

struct AirportViewModel: AirportViewPresentable {
    
    var formattedDistance: String {
        return "\((self.distance?.rounded(.up) ?? 0) / 1000) Km"
    }
    var name: String
    var code: String
    var address: String
    var distance: Double?
    var runawayLength: String
    var location: (lat: String, lon: String)
}

extension AirportViewModel {
    init(usingModel model: AirportModel, currentLocation: (lat: Double, lon: Double)) {
        self.name = model.name
        self.code = model.code
        self.address = "\(model.state ?? ""), \(model.country)"
        self.runawayLength = "Runaway: \(model.runwayLength ?? "")"
        self.location = (model.lat, model.lon)
        // 当前位置到坐标点的距离 需要计算
        let distance = AirportViewModel.getDistance(currentLocation: currentLocation,
                                                     airportLocation: (lat: Double(model.lat), lon: Double(model.lon)))
        
        self.distance = distance
    }
}

extension AirportViewModel {
    
    static func getDistance(currentLocation:(lat: Double, lon: Double), airportLocation:(lat: Double?, lon: Double?)) -> Double? {
        
        guard
            let airportLat = airportLocation.lat,
            let airportLon = airportLocation.lon else { return nil }
        
        let current = CLLocation(latitude: currentLocation.lat,
                                 longitude: currentLocation.lon)
        
        let airport = CLLocation(latitude: airportLat,
                                 longitude: airportLon)
        
        return  current.distance(from: airport)
    }
}

extension AirportViewModel: Comparable {
    
    static func == (lhs: AirportViewModel, rhs: AirportViewModel) -> Bool {
        return lhs.distance ?? 0 < rhs.distance ?? 0
    }
    
    static func < (lhs: AirportViewModel, rhs: AirportViewModel) -> Bool {
        return lhs.code == rhs.code
    }
    
}
